<?php
namespace app\controllers\api\post;

use fate\http\Request;
use app\models\Posts;
use app\libs\Util;

class RelativeController extends \fate\web\PureController {
    public function run() {
        $req = Request::getInstance();

        $tags = Util::plainText($req->getQueryString('tags'));
        $postId = $req->getQueryString('post_id');

        if(!is_numeric($postId)) {
            $this->ajaxReturn(null, 300002);
            exit;
        }

        $tagsArr = explode(',', $tags);  // ['a', 'b'];
        $relative_where = $this->buildTagWhere($tagsArr);
        //echo $relative_where;exit;

        $post = new Posts();
        $relate = $post->getListByCondition(
            'id,title,tags,thumb,brief,post_time',
            'id<>'. $postId . ' and status=1 and ('. $relative_where .')',
            5, 'id desc'
        );

        $this->ajaxReturn([
            'data' => $relate
        ]);
    }

    public function buildTagWhere(& $tagsArr) {
        $ret = [];

        foreach($tagsArr as $v) {
            $ret[] = "instr(tags, '{$v}')";
        }

        return implode(' or ', $ret);
    }
}
